package com.libweb.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import java.util.Calendar;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.libweb.common.Util;
import com.libweb.model.dao.BookDao;
import com.libweb.model.dto.Book;

@WebServlet("/book/register.action")
public class BookRegisterServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException {
		
		String Title = req.getParameter("title");
		String Publisher = req.getParameter("publisher");
		String Author = req.getParameter("author");
		
		String pubDateString = req.getParameter("pubdate");
		int year = Integer.parseInt(pubDateString.substring(0, 4));
		int month = Integer.parseInt(pubDateString.substring(4, 6));
		int day = Integer.parseInt(pubDateString.substring(6));
		
		Calendar c = Calendar.getInstance();
		c.set(Calendar.YEAR, year);
		c.set(Calendar.MONTH, month);
		c.set(Calendar.DAY_OF_MONTH, day);
		
		Date pubDate = new Date(c.getTimeInMillis());
		
		Book book = new Book();
		book.setTitle(Title);
		book.setPublisher(Publisher);
		book.setAuthor(Author);
		book.setPubDate(pubDate);
		
		BookDao dao = new BookDao();
		dao.insertBook(book);
		
		//등록 후 목록 화면으로 이동
		//HttpResponse.sendRedirect: 지정된 경로로 요청을 재전송
		resp.sendRedirect("/libweb/book/list.action");
		
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException {
		
		req.setCharacterEncoding("utf-8");
		
		doGet(req, resp);
	}
	
}